<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>
      <a-modal
        width="1000px"
        v-model="modleVisible"
        :title="form.id ? '编辑场站' : '新增场站'"
        @cancel="() => (this.modleVisible = false)"
        :confirm-loading="formButtonDisableFlag"
        @ok="onSubmit"
      >
        <div id="modalContent">
          <div class="formAspin" v-if="editWaitForLoading">
            <a-spin />
          </div>
          <div class="modalContentForm">
            <a-form-model
              ref="formRef"
              :model="form"
              :rules="rules"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
            >
              <a-row type="flex" justify="space-between">
                <a-col :span="12">
                  <Input :form="form" label="场站名称" prop="name" placeholder="请输入场站名称"></Input>
                </a-col>
                <a-col :span="12">
                  <Input :form="form" label="场站编号" prop="code" placeholder="请输入场站编号"></Input>
                </a-col>
                <a-col :span="12">
                  <treeSelect
                    :form="form"
                    label="所属组织"
                    prop="organizationId"
                    placeholder="请选择组织"
                    :treeData="oDictionary.organizationsTree"
                  ></treeSelect>
                </a-col>
                <a-col :span="12">
                  <Input :form="form" label="联系人" prop="contact" placeholder="请输入联系人"></Input>
                </a-col>
                <a-col :span="12">
                  <Input :form="form" label="联系电话" prop="contactPhone" placeholder="请输入联系电话"></Input>
                </a-col>
                <a-col :span="12">
                  <InputNumber
                    :form="form"
                    label="电价"
                    prop="electrovalence"
                    placeholder="请输入电价"
                    :precision="2"
                    suffix="元"
                  ></InputNumber>
                </a-col>
                <a-col :span="12">
                  <Select
                    :form="form"
                    label="是否私有"
                    prop="type"
                    placeholder="请选择是否私有"
                    :optList="[
                      { name: '是', code: '1' },
                      { name: '否', code: '0' },
                    ]"
                  ></Select>
                </a-col>
                <a-col :span="12">
                  <Input :form="form" label="地址" prop="address" placeholder="请输入地址"></Input>
                </a-col>
                <!-- <a-col :span="12">
                  <Select
                    :form="form"
                    label="状态"
                    prop="isEnable"
                    placeholder="请选择状态"
                    :optList="getIsEnableOption()"
                  ></Select>
                </a-col> -->
                <a-col :span="12">
                  <Input :form="form" label="备注" prop="remark" placeholder="请输入备注"></Input>
                </a-col>
                <a-col :span="24">
                  <a-col :span="12">
                    <Input :form="form" label="经度" prop="lng" placeholder="点击地图自动生成经度" readonly></Input>
                  </a-col>
                  <a-col :span="12">
                    <Input :form="form" label="纬度" prop="lat" placeholder="点击地图自动生成纬度" readonly></Input>
                  </a-col>
                </a-col>
              </a-row>
            </a-form-model>
            <MapBox ref="map" @click="mapClick" :isInverseAnalysis="true"></MapBox>
          </div>
        </div>
      </a-modal>
      <typicalSearch ref="insideSearch" :searchConfig="searchConfig" @searchMethod="getTableData"></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">场站管理</div>
          <div class="addButton">
            <a-button type="primary" @click="handleEdit()"> 新增场站 </a-button>
          </div>
        </div>
        <div class="tableList">
          <typicalTable
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
          >
            <template v-slot="slotProps">
              <Button label="编辑" @click="handleEdit(slotProps.record)"></Button>
              <a-popconfirm
                slot="action"
                title="此操作将删除该条数据，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(slotProps.record)"
              >
                <Button type="stop" label="删除"></Button>
              </a-popconfirm>
              <Button
                :type="slotProps.record.status === 0 ? 'start' : 'stop'"
                @click="fnStartStop(slotProps.record)"
              ></Button>
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import InputNumber from '@/components/typicalControl/InputNumber';
import treeSelect from '@/components/typicalControl/treeSelect';
import Select from '@/components/typicalControl/select';
import MapBox from '@/components/map';
import Button from '@/components/typicalControl/button';
import { getYesNo, getIsEnableOption } from '@/utils/frequentInterface';
import { recursionTreeDisabled } from '@/utils/tool';

import { organizationsTree } from '@/api/system';
import { listNetworksAll } from '@/api/cabin';

export default {
  name: 'BusinessOutlets',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Input: Input,
    InputNumber: InputNumber,
    treeSelect: treeSelect,
    Button: Button,
    Select: Select,
    MapBox: MapBox,
  },
  data() {
    return {
      formButtonDisableFlag: false, // 表单确定禁用按钮 防止多次点击多次保存
      editWaitForLoading: false, // 加载编辑回显数据等待Loading
      roleLoading: false, // 加载表格的loading
      modleVisible: false, // 控制弹框
      form: {
        address: undefined,
        code: undefined,
        contact: undefined,
        contactPhone: undefined,
        electrovalence: undefined,
        lng: undefined,
        lat: undefined,
        name: undefined,
        organizationId: undefined,
        remark: undefined,
        type: undefined,
      },
      rules: {
        // 规则验证
        name: [
          { required: true, message: '请输入场站名称', trigger: 'blur' },
          { max: 25, message: '最大长度不能超过25个字', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请输入场站编号', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' },
        ],
        address: [
          { required: true, message: '请输入场站地址', trigger: 'blur' },
          { max: 90, message: '最大长度不能超过90个字', trigger: 'blur' },
        ],
        contact: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' },
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { max: 45, message: '最大长度不能超过45个字', trigger: 'blur' },
        ],
        electrovalence: [{ required: true, message: '请输入电价', trigger: 'blur' }],
        organizationId: [{ required: true, message: '请选择组织机构', trigger: 'change' }],
        type: [{ required: true, message: '请选择是否私有', trigger: 'change' }],
        lng: [{ required: true, message: '请点击地图自动生成经度', trigger: 'blur' }],
        lat: [{ required: true, message: '请点击地图自动生成纬度', trigger: 'blur' }],
      },
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'input',
            prop: 'searchName',
            value: '',
            label: '场站名称',
          },
          {
            type: 'input',
            prop: 'searchCode',
            value: '',
            label: '场站编号',
          },
          {
            type: 'selectTree',
            prop: 'searchOrganizationId',
            value: undefined,
            label: '所属组织',
            treeData: [],
          },
        ],
        parent: this,
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '场站名称',
            dataIndex: 'name',
            ellipsis: true,
          },
          {
            title: '所属组织',
            dataIndex: 'organizationName',
            ellipsis: true,
          },
          {
            title: '场站编号',
            dataIndex: 'code',
            ellipsis: true,
          },
          {
            title: '联系人',
            dataIndex: 'contact',
            ellipsis: true,
          },
          {
            title: '联系电话 ',
            dataIndex: 'contactPhone',
            ellipsis: true,
          },
          {
            title: '场站备注',
            dataIndex: 'remark',
            ellipsis: true,
          },
          {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' },
            width: '80px',
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            ellipsis: true,
            width: '180px',
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      oDictionary: {
        organizationsTree: [],
      },
    };
  },
  created() {
    this.getDictionary();
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    getYesNo,
    getIsEnableOption,
    /**
     * [getDictionary 获取各种字典]
     * @return {[type]} [description]
     */
    getDictionary() {
      // 组织列表树形结构数据
      organizationsTree().then((res) => {
        if (res.code == 200) {
          recursionTreeDisabled(res.data);
          this.oDictionary.organizationsTree = res.data;
          for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
            if (this.searchConfig.formItemList[i].prop === 'searchOrganizationId') {
              this.searchConfig.formItemList[i].treeData = res.data;
              break;
            }
          }
        }
      });
    },
    /**
     * [fnStartStop 启用停用方法]
     * @param  {[type]} row [行数据]
     * @return {[type]}     [description]
     */
    fnStartStop(row) {
      let msg = row.status == 1 ? '停用' : '启用';
      this.$confirm({
        title: '提示',
        content: (h) => `确定要${msg}吗？`,
        onOk: () => this.doStartStop(row),
        centered: true,
        maskClosable: true,
      });
    },
    doStartStop(row) {
      this.roleLoading = true;
      listNetworksAll(`/stopAndStartChargingnetwork/${row.id}`, 'put')
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(row.status == 0 ? '启用成功' : '停用成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      if (!searchParam) throw new Error('getTableData 没有入参搜索条件！');
      this.roleLoading = true;
      searchParam.searchDataRang = 9;
      let params = {
        pageNum: searchParam.pageNumber + 1,
        pageSize: searchParam.pageSize,
        code: searchParam.searchCode,
        name: searchParam.searchName,
        organizationId: searchParam.searchOrganizationId,
      };
      listNetworksAll(`/selectChargingnetwork`, 'get', params)
        .then((res) => {
          if (res.code == 200 && res.data.records) {
            this.tableData = res.data;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * @description: 新增编辑场站表单提交
     */
    onSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          let msg = this.form.id ? '编辑' : '新增';
          this.$confirm({
            title: '提示',
            content: (h) => `确定要${msg}场站吗？`,
            onOk: () => this.doOperate(),
            centered: true,
            maskClosable: true,
          });
        } else {
          return false;
        }
      });
    },
    doOperate() {
      this.formButtonDisableFlag = true;
      if (this.form.id) {
        this.editRole(this.form);
      } else {
        this.roleAdd(this.form);
      }
    },

    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      return {
        address: undefined,
        code: undefined,
        contact: undefined,
        contactPhone: undefined,
        electrovalence: undefined,
        lng: undefined,
        lat: undefined,
        name: undefined,
        organizationId: undefined,
        remark: undefined,
        type: undefined,
      };
    },

    /**
     * @description: 新增场站权限
     * @param {object} addRoleParam 表单参数
     */
    roleAdd(addRoleParam) {
      listNetworksAll('/insertChargingnetwork', 'post', addRoleParam)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('新增场站成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 编辑场站权限
     * @param {object} editRoleParam 表单参数
     */
    editRole(editRoleParam) {
      listNetworksAll('/updateChargingnetwork', 'put', editRoleParam)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('编辑成功');
            this.formSuccessOperation(res);
          }
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 表单新增编辑成功后的公共的代码 （消息提示 搜索框重置 请求表格数据）
     * @param {object} successFormData 表单请求成功后返回的对象
     */
    formSuccessOperation(successFormData) {
      this.modleVisible = false;
      this.$refs.insideTable.updateListData();
    },

    /**
     * [handleEdit 新增或编辑]
     * @param  {[type]} row [如果编辑入参行数据]
     * @return {[type]}     [description]
     */
    handleEdit(row) {
      this.modleVisible = true;
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.form = this.initializationForm();
      if (this.$refs.map) {
        this.$refs.map.manualDestroy();
      }
      if (row) {
        this.form = { ...row };
        if (this.form.lat && this.form.lng) {
          this.$nextTick(() => {
            this.$refs.map.addMarker({ lat: this.form.lat, lng: this.form.lng });
          });
        }
      }
    },

    /**
     * @description: 点击删除
     * @param {object} roleTableRowData 格某一行的数据对象
     */
    handleDelete(roleTableRowData) {
      listNetworksAll(`/updateChargingNetwork/${roleTableRowData.id}`, 'put').then((res) => {
        if (res.code == 200) {
          this.$message.success('删除成功');
          this.$refs.insideTable.updateListData();
        }
      });
    },
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    },

    /**
     * [mapClick 地图点击事件]
     * @param  {[type]} e [点击携带数据]
     * @return {[type]}   [description]
     */
    mapClick(e) {
      this.form.lng = this.toPrecisionSix(e.latLng.lng);
      this.form.lat = this.toPrecisionSix(e.latLng.lat);
      // this.form.area = {
      //   id: e.result.ad_info.adcode
      // };
      if (e.address) {
        this.form.address = e.address;
      }
    },

    /**
     * [toPrecisionSix 保留小数点6位数]
     * @param  {[type]} val [数字]
     * @return {[type]}     [description]
     */
    toPrecisionSix(val) {
      return parseInt(val * 1000000) / 1000000;
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 600px;
  overflow: auto;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 600px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
/deep/ .ant-col .ant-col-4{
  width: 20.666667%;
}
</style>
